import { userlist, usercount } from "@/request/api";

interface StateUser {
    userList: Array<object>,
    page: Number,
    size: Number,
    count: Number
}


const state = {
    userList: [],
    size: 2,//每一页展示几条数据
    page: 1,//当前页
    count: 0,//总条数
}

const mutations = {
    // 修改管理员列表
    USER_LIST(state: StateUser, payload: any) {
        state.userList = payload;
    },
    // 修改总条数
    COUNT(state: StateUser, payload: any) {
        state.count = payload;
    },
    // 更改页码
    CHANGE_SIZE(state: StateUser, payload: any) {
        state.page = payload;

    }
}

const actions = {
    // 获取管理员列表
    getUserListActions(context: any) {
        userlist({
            size: context.state.size,
            page: context.state.page
        }).then((res: any) => {
            if (res.code == 200) {
                // 删除除了第一页的最后一条数据会显示暂无数据 所以在page不等于1是 并且返回的数据为null时 让page-1
                let list = res.list?res.list:null
                
                if (context.state.page != 1 && list == null ) {
                    
                    context.dispatch('change_size', context.state.page - 1)

                }
                context.commit('USER_LIST', res.list);
            }
        })
    },
    // 获取总条数
    getCountActions(context: any) {
        usercount().then((res: any) => {
            if (res.code == 200) {
                context.commit('COUNT', res.list[0].total)
            }
        })
    },
    // 更改页码  重新渲染视图
    change_size(context: any, payload: Number) {
        console.log(payload);
        context.commit('CHANGE_SIZE', payload)
        context.dispatch('getUserListActions')

    }


}

const getters = {
    getUserList(state: StateUser) {
        return state.userList
    },
    getSize(state: StateUser) {
        return state.size
    },
    getCount(state: StateUser) {
        return state.count
    },
}

export default {
    state,
    mutations,
    actions,
    getters,
    namespaced: true
}